package com.meta.utils
{
	import flash.external.ExternalInterface;

	import mx.core.FlexGlobals;

	/**
	 * js 调用 as 简单实现
	 * 复杂应用场景 参考JSPort 类
	 * @author BOBO
	 */
	public class JSUtils
	{
		/**
		 *
		 */
		public function JSUtils()
		{
		}

		/**
		 * 获取 查询 参数
		 * @param url
		 * @return
		 */
		public static function getQuery(url:String=''):Object
		{
			var urlString:String=url ? url : ExternalInterface.call("window.location.href.toString");
			var o:Object;
			if (urlString.indexOf('?') != -1)
			{
				var query:String=urlString.split('?')[1];
				if (query)
				{
					o={};
					var a1:Array=query.split('&');
					for each (var s:String in a1)
					{
						var a2:Array=s.split('=');
						if (a2.length == 2)
						{
							var value:String=a2[1];
							var uv:String;
							if (value && value.indexOf('http') == 0)
							{
								uv=unescape(value);
								o[a2[0]]=uv;
							}
							else
							{
								o[a2[0]]=decodeURI(value);
							}
						}

					}
				}
			}
			return o;
		}

		/**
		 *
		 * @param _mainController 初始化
		 */
		public static function init(_mainController:*):void
		{
			mainController = _mainController;
			params = FlexGlobals.topLevelApplication.parameters;
			ExternalInterface.addCallback("callAS",onJSCall);//js调用as
		}

		private static var mainController:Object;

		/**
		 *
		 * @param functionName 方法名 与mc中方法对应
		 * @param params 方法参数
		 */
		public static function onJSCall(functionName:String,...params):void
		{
			if(params.length==1&&params[0] is Array)
				params = params[0];
//			try
//			{
			(mainController[functionName] as Function).apply(mainController,params);
//			}
//			catch(error:Error) 
//			{
//				trace(error.message);
//			}
		}

		public static var params:Object;

		public static function refresh():void
		{
			ExternalInterface.call('refresh');
		}

		public static function backtomain():void
		{
			ExternalInterface.call('backtomain');
		}

	}
}

